<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Set、WeakSet、Map及WeakMap | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,ES6,">
  

  <meta name="description" content="Set 和 Map 主要的应用场景在于 数据重组 和 数据储存 Set 是一种叫做集合的数据结构，Map 是一种叫做字典的数据结构  1. 集合（Set） ES6 新增的一种新的数据结构，类似于数组，但成员是唯一且无序的，没有重复的值。  Set 本身是一种构造函数，用来生成 Set 数据结构。 new Set([iterable]) 举个例子： const s = new Set()[1, 2">
<meta name="keywords" content="JavaScript,ES6">
<meta property="og:type" content="article">
<meta property="og:title" content="Set、WeakSet、Map及WeakMap">
<meta property="og:url" content="http://blog.poetries.top/2019/09/22/es6-set-weakSet-map-weakMap/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="Set 和 Map 主要的应用场景在于 数据重组 和 数据储存 Set 是一种叫做集合的数据结构，Map 是一种叫做字典的数据结构  1. 集合（Set） ES6 新增的一种新的数据结构，类似于数组，但成员是唯一且无序的，没有重复的值。  Set 本身是一种构造函数，用来生成 Set 数据结构。 new Set([iterable]) 举个例子： const s = new Set()[1, 2">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-images.githubusercontent.com/19721451/54000905-3d36c980-4184-11e9-9ccf-0f13bc6dd414.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.906Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Set、WeakSet、Map及WeakMap">
<meta name="twitter:description" content="Set 和 Map 主要的应用场景在于 数据重组 和 数据储存 Set 是一种叫做集合的数据结构，Map 是一种叫做字典的数据结构  1. 集合（Set） ES6 新增的一种新的数据结构，类似于数组，但成员是唯一且无序的，没有重复的值。  Set 本身是一种构造函数，用来生成 Set 数据结构。 new Set([iterable]) 举个例子： const s = new Set()[1, 2">
<meta name="twitter:image" content="https://user-images.githubusercontent.com/19721451/54000905-3d36c980-4184-11e9-9ccf-0f13bc6dd414.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-集合（Set）"><span class="toc-text">1. 集合（Set）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-WeakSet"><span class="toc-text">2. WeakSet</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-字典（Map）"><span class="toc-text">3. 字典（Map）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-WeakMap"><span class="toc-text">4. WeakMap</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-总结"><span class="toc-text">5. 总结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-扩展：Object与Set、Map"><span class="toc-text">6. 扩展：Object与Set、Map</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-es6-set-weakSet-map-weakMap" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Set、WeakSet、Map及WeakMap</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.09.22</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2.8k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 12分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <ul>
<li><code>Set</code> 和 <code>Map</code> 主要的应用场景在于 <strong>数据重组</strong> 和 <strong>数据储存</strong></li>
<li><code>Set</code> 是一种叫做<strong>集合</strong>的数据结构，Map 是一种叫做<strong>字典</strong>的数据结构</li>
</ul>
<h3 id="1-集合（Set）"><a href="#1-集合（Set）" class="headerlink" title="1. 集合（Set）"></a>1. 集合（Set）</h3><blockquote>
<p><code>ES6</code> 新增的一种新的数据结构，类似于数组，但成员是唯一且无序的，没有重复的值。</p>
</blockquote>
<p><strong>Set 本身是一种构造函数，用来生成 Set 数据结构。</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Set</span>([iterable])</span><br></pre></td></tr></table></figure>
<p>举个例子：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> s = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>].forEach(<span class="function"><span class="params">x</span> =&gt;</span> s.add(x))</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">of</span> s) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(i)	<span class="comment">// 1 2 3 4</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 去重数组的重复对象</span></span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">1</span>]</span><br><span class="line">[... new <span class="built_in">Set</span>(arr)]	<span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>
<p>Set 对象允许你储存任何类型的唯一值，无论是原始值或者是对象引用。</p>
<p>向 Set 加入值的时候，不会发生类型转换，所以<code>5</code>和<code>&quot;5&quot;</code>是两个不同的值。Set 内部判断两个值是否不同，使用的算法叫做“Same-value-zero equality”，它类似于<strong>精确相等</strong>运算符（<code>===</code>），主要的区别是<strong> Set 认为<code>NaN</code>等于自身，而精确相等运算符认为<code>NaN</code>不等于自身。</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set();</span><br><span class="line">let a = NaN;</span><br><span class="line">let b = NaN;</span><br><span class="line"><span class="keyword">set</span>.add(a);</span><br><span class="line"><span class="keyword">set</span>.add(b);</span><br><span class="line"><span class="keyword">set</span> // Set &#123;<span class="literal">NaN</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">set1.add(<span class="number">5</span>)</span><br><span class="line">set1.add(<span class="string">'5'</span>)</span><br><span class="line"><span class="built_in">console</span>.log([...set1])	<span class="comment">// [5, "5"]</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p>Set 实例属性</p>
<ul>
<li><p>constructor： 构造函数</p>
</li>
<li><p>size：元素数量</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set([1, 2, 3, 2, 1])</span><br><span class="line"></span><br><span class="line">console.log(<span class="keyword">set</span>.length)	// undefined</span><br><span class="line">console.log(<span class="keyword">set</span>.size)	// 3</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>Set 实例方法</p>
<ul>
<li><p>操作方法</p>
<ul>
<li><p>add(value)：新增，相当于 array里的push</p>
</li>
<li><p>delete(value)：存在即删除集合中value</p>
</li>
<li><p>has(value)：判断集合中是否存在 value</p>
</li>
<li><p>clear()：清空集合</p>
<hr>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set()</span><br><span class="line"><span class="keyword">set</span>.add(1).add(2).add(1)</span><br><span class="line"></span><br><span class="line"><span class="keyword">set</span>.has(1)	// true</span><br><span class="line"><span class="keyword">set</span>.has(3)	// false</span><br><span class="line"><span class="keyword">set</span>.delete(1)	</span><br><span class="line"><span class="keyword">set</span>.has(1)	// false</span><br></pre></td></tr></table></figure>
<p><code>Array.from</code> 方法可以将 Set 结构转为数组</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> items = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">2</span>])</span><br><span class="line"><span class="keyword">const</span> array = <span class="built_in">Array</span>.from(items)</span><br><span class="line"><span class="built_in">console</span>.log(array)	<span class="comment">// [1, 2, 3]</span></span><br><span class="line"><span class="comment">// 或</span></span><br><span class="line"><span class="keyword">const</span> arr = [...items]</span><br><span class="line"><span class="built_in">console</span>.log(arr)	<span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>遍历方法（遍历顺序为插入顺序）</p>
<ul>
<li><p>keys()：返回一个包含集合中所有键的迭代器</p>
</li>
<li><p>values()：返回一个包含集合中所有值得迭代器</p>
</li>
<li><p>entries()：返回一个包含Set对象中所有元素得键值对迭代器</p>
</li>
<li><p>forEach(callbackFn,  thisArg)：用于对集合成员执行callbackFn操作，如果提供了 thisArg 参数，回调中的this会是这个参数，<strong>没有返回值</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set([1, 2, 3])</span><br><span class="line">console.log(<span class="keyword">set</span>.keys())	// SetIterator &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">set</span>.values())	// SetIterator &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">set</span>.entries())	// SetIterator &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> item <span class="keyword">of</span> <span class="keyword">set</span>.keys()) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(item);</span><br><span class="line">&#125;	<span class="comment">// 1	2	 3</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> item <span class="keyword">of</span> <span class="keyword">set</span>.entries()) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(item);</span><br><span class="line">&#125;	<span class="comment">// [1, 1]	[2, 2]	[3, 3]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">set</span>.forEach((value, key) =&gt;  &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(key + <span class="string">' : '</span> + value)</span><br><span class="line">&#125;)	<span class="comment">// 1 : 1	2 : 2		3 : 3</span></span><br><span class="line"><span class="built_in">console</span>.log([...set])	<span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>
<p>Set 可默认遍历，默认迭代器生成函数是 values() 方法</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">Set</span>.prototype[<span class="built_in">Symbol</span>.iterator] === <span class="built_in">Set</span>.prototype.values	<span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>所以， Set可以使用 map、filter 方法</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set([1, 2, 3])</span><br><span class="line"><span class="keyword">set</span> = new Set([...<span class="keyword">set</span>].map(item =&gt; item * 2))</span><br><span class="line">console.log([...<span class="keyword">set</span>])	// [2, 4, 6]</span><br><span class="line"></span><br><span class="line"><span class="keyword">set</span> = new Set([...<span class="keyword">set</span>].filter(item =&gt; (item &gt;= 4)))</span><br><span class="line">console.log([...<span class="keyword">set</span>])	//[4, 6]</span><br></pre></td></tr></table></figure>
<p>因此，Set 很容易实现交集（Intersect）、并集（Union）、差集（Difference）</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line"><span class="keyword">let</span> set2 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> intersect = <span class="keyword">new</span> <span class="built_in">Set</span>([...set1].filter(<span class="function"><span class="params">value</span> =&gt;</span> set2.has(value)))</span><br><span class="line"><span class="keyword">let</span> union = <span class="keyword">new</span> <span class="built_in">Set</span>([...set1, ...set2])</span><br><span class="line"><span class="keyword">let</span> difference = <span class="keyword">new</span> <span class="built_in">Set</span>([...set1].filter(<span class="function"><span class="params">value</span> =&gt;</span> !set2.has(value)))</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(intersect)	<span class="comment">// Set &#123;2, 3&#125;</span></span><br><span class="line"><span class="built_in">console</span>.log(union)		<span class="comment">// Set &#123;1, 2, 3, 4&#125;</span></span><br><span class="line"><span class="built_in">console</span>.log(difference)	<span class="comment">// Set &#123;1&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="2-WeakSet"><a href="#2-WeakSet" class="headerlink" title="2. WeakSet"></a>2. WeakSet</h3><p>WeakSet 对象允许你将<strong>弱引用对象</strong>储存在一个集合中</p>
<p>WeakSet 与 Set 的区别：</p>
<ul>
<li>WeakSet 只能储存对象引用，不能存放值，而 Set 对象都可以</li>
<li>WeakSet 对象中储存的对象值都是被弱引用的，即垃圾回收机制不考虑 WeakSet 对该对象的应用，如果没有其他的变量或属性引用这个对象值，则这个对象将会被垃圾回收掉（不考虑该对象还存在于 WeakSet 中），所以，WeakSet 对象里有多少个成员元素，取决于垃圾回收机制有没有运行，运行前后成员个数可能不一致，遍历结束之后，有的成员可能取不到了（被垃圾回收了），WeakSet 对象是无法被遍历的（ES6 规定 WeakSet 不可遍历），也没有办法拿到它包含的所有元素</li>
</ul>
<p>属性：</p>
<ul>
<li><p>constructor：构造函数，任何一个具有 Iterable 接口的对象，都可以作参数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [[<span class="number">1</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line"><span class="keyword">const</span> weakset = <span class="keyword">new</span> <span class="built_in">WeakSet</span>(arr)</span><br><span class="line"><span class="built_in">console</span>.log(weakset)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><img width="677" alt="2019-03-08 9 24 34" src="https://user-images.githubusercontent.com/19721451/54000905-3d36c980-4184-11e9-9ccf-0f13bc6dd414.png"></p>
<p>方法：</p>
<ul>
<li>add(value)：在WeakSet 对象中添加一个元素value</li>
<li>has(value)：判断 WeakSet 对象中是否包含value</li>
<li>delete(value)：删除元素 value</li>
<li>clear()：清空所有元素，<strong>注意该方法已废弃</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> ws = <span class="keyword">new</span> <span class="built_in">WeakSet</span>()</span><br><span class="line"><span class="keyword">var</span> obj = &#123;&#125;</span><br><span class="line"><span class="keyword">var</span> foo = &#123;&#125;</span><br><span class="line"></span><br><span class="line">ws.add(<span class="built_in">window</span>)</span><br><span class="line">ws.add(obj)</span><br><span class="line"></span><br><span class="line">ws.has(<span class="built_in">window</span>)	<span class="comment">// true</span></span><br><span class="line">ws.has(foo)	<span class="comment">// false</span></span><br><span class="line"></span><br><span class="line">ws.delete(<span class="built_in">window</span>)	<span class="comment">// true</span></span><br><span class="line">ws.has(<span class="built_in">window</span>)	<span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<h3 id="3-字典（Map）"><a href="#3-字典（Map）" class="headerlink" title="3. 字典（Map）"></a>3. 字典（Map）</h3><p>集合 与 字典 的区别：</p>
<ul>
<li>共同点：集合、字典 可以储存不重复的值</li>
<li>不同点：集合 是以 [value, value]的形式储存元素，字典 是以 [key, value] 的形式储存</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> m = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line"><span class="keyword">const</span> o = &#123;<span class="attr">p</span>: <span class="string">'haha'</span>&#125;</span><br><span class="line">m.set(o, <span class="string">'content'</span>)</span><br><span class="line">m.get(o)	<span class="comment">// content</span></span><br><span class="line"></span><br><span class="line">m.has(o)	<span class="comment">// true</span></span><br><span class="line">m.delete(o)	<span class="comment">// true</span></span><br><span class="line">m.has(o)	<span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p><strong>任何具有 Iterator 接口、且每个成员都是一个双元素的数组的数据结构</strong>都可以当作<code>Map</code>构造函数的参数，例如：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">set</span> = new Set([</span><br><span class="line">  ['foo', 1],</span><br><span class="line">  ['bar', 2]</span><br><span class="line">]);</span><br><span class="line">const m1 = new Map(<span class="keyword">set</span>);</span><br><span class="line">m1.<span class="keyword">get</span>('foo') // 1</span><br><span class="line"></span><br><span class="line">const m2 = new Map([['baz', 3]]);</span><br><span class="line">const m3 = new Map(m2);</span><br><span class="line">m3.<span class="keyword">get</span>('baz') // 3</span><br></pre></td></tr></table></figure>
<p>如果读取一个未知的键，则返回<code>undefined</code>。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">new Map().get(&apos;asfddfsasadf&apos;)</span><br><span class="line">// undefined</span><br></pre></td></tr></table></figure>
<p>注意，只有对同一个对象的引用，Map 结构才将其视为同一个键。这一点要非常小心。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const map = new Map();</span><br><span class="line"></span><br><span class="line">map.set([&apos;a&apos;], 555);</span><br><span class="line">map.get([&apos;a&apos;]) // undefined</span><br></pre></td></tr></table></figure>
<p>上面代码的<code>set</code>和<code>get</code>方法，表面是针对同一个键，但实际上这是两个值，内存地址是不一样的，因此<code>get</code>方法无法读取该键，返回<code>undefined</code>。</p>
<p>由上可知，Map 的键实际上是跟内存地址绑定的，只要内存地址不一样，就视为两个键。这就解决了同名属性碰撞（clash）的问题，我们扩展别人的库的时候，如果使用对象作为键名，就不用担心自己的属性与原作者的属性同名。</p>
<p>如果 Map 的键是一个简单类型的值（数字、字符串、布尔值），则只要两个值严格相等，Map 将其视为一个键，比如<code>0</code>和<code>-0</code>就是一个键，布尔值<code>true</code>和字符串<code>true</code>则是两个不同的键。另外，<code>undefined</code>和<code>null</code>也是两个不同的键。虽然<code>NaN</code>不严格相等于自身，但 Map 将其视为同一个键。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">let map = new Map();</span><br><span class="line"></span><br><span class="line">map.set(-0, 123);</span><br><span class="line">map.get(+0) // 123</span><br><span class="line"></span><br><span class="line">map.set(true, 1);</span><br><span class="line">map.set(&apos;true&apos;, 2);</span><br><span class="line">map.get(true) // 1</span><br><span class="line"></span><br><span class="line">map.set(undefined, 3);</span><br><span class="line">map.set(null, 4);</span><br><span class="line">map.get(undefined) // 3</span><br><span class="line"></span><br><span class="line">map.set(NaN, 123);</span><br><span class="line">map.get(NaN) // 123</span><br></pre></td></tr></table></figure>
<p>Map 的属性及方法</p>
<p>属性：</p>
<ul>
<li><p>constructor：构造函数</p>
</li>
<li><p>size：返回字典中所包含的元素个数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [<span class="string">'name'</span>, <span class="string">'An'</span>],</span><br><span class="line">  [<span class="string">'des'</span>, <span class="string">'JS'</span>]</span><br><span class="line">]);</span><br><span class="line"></span><br><span class="line">map.size <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>操作方法：</p>
<ul>
<li>set(key, value)：向字典中添加新元素</li>
<li>get(key)：通过键查找特定的数值并返回</li>
<li>has(key)：判断字典中是否存在键key</li>
<li>delete(key)：通过键 key 从字典中移除对应的数据</li>
<li>clear()：将这个字典中的所有元素删除</li>
</ul>
<p>遍历方法</p>
<ul>
<li>Keys()：将字典中包含的所有键名以迭代器形式返回</li>
<li>values()：将字典中包含的所有数值以迭代器形式返回</li>
<li>entries()：返回所有成员的迭代器</li>
<li>forEach()：遍历字典的所有成员</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">            [<span class="string">'name'</span>, <span class="string">'An'</span>],</span><br><span class="line">            [<span class="string">'des'</span>, <span class="string">'JS'</span>]</span><br><span class="line">        ]);</span><br><span class="line"><span class="built_in">console</span>.log(map.entries())	<span class="comment">// MapIterator &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span></span><br><span class="line"><span class="built_in">console</span>.log(map.keys()) <span class="comment">// MapIterator &#123;"name", "des"&#125;</span></span><br></pre></td></tr></table></figure>
<p>Map 结构的默认遍历器接口（<code>Symbol.iterator</code>属性），就是<code>entries</code>方法。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">map[Symbol.iterator] === map.entries</span><br><span class="line">// true</span><br></pre></td></tr></table></figure>
<p>Map 结构转为数组结构，比较快速的方法是使用扩展运算符（<code>...</code>）。</p>
<p>对于 forEach ，看一个例子</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> reporter = &#123;</span><br><span class="line">  report: <span class="function"><span class="keyword">function</span>(<span class="params">key, value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Key: %s, Value: %s"</span>, key, value);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">    [<span class="string">'name'</span>, <span class="string">'An'</span>],</span><br><span class="line">    [<span class="string">'des'</span>, <span class="string">'JS'</span>]</span><br><span class="line">])</span><br><span class="line">map.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">value, key, map</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.report(key, value);</span><br><span class="line">&#125;, reporter);</span><br><span class="line"><span class="comment">// Key: name, Value: An</span></span><br><span class="line"><span class="comment">// Key: des, Value: JS</span></span><br></pre></td></tr></table></figure>
<p>在这个例子中， forEach 方法的回调函数的 this，就指向 reporter</p>
<p><strong>与其他数据结构的相互转换</strong></p>
<ol>
<li><p>Map 转 Array</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="number">1</span>, <span class="number">1</span>], [<span class="number">2</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">3</span>]])</span><br><span class="line"><span class="built_in">console</span>.log([...map])	<span class="comment">// [[1, 1], [2, 2], [3, 3]]</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="2">
<li><p>Array 转 Map</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="number">1</span>, <span class="number">1</span>], [<span class="number">2</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">3</span>]])</span><br><span class="line"><span class="built_in">console</span>.log(map)	<span class="comment">// Map &#123;1 =&gt; 1, 2 =&gt; 2, 3 =&gt; 3&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="3">
<li><p>Map 转 Object</p>
<p>因为 Object 的键名都为字符串，而Map 的键名为对象，所以转换的时候会把非字符串键名转换为字符串键名。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mapToObj</span>(<span class="params">map</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> obj = <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> [key, value] <span class="keyword">of</span> map) &#123;</span><br><span class="line">        obj[key] = value</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>().set(<span class="string">'name'</span>, <span class="string">'An'</span>).set(<span class="string">'des'</span>, <span class="string">'JS'</span>)</span><br><span class="line">mapToObj(map) <span class="comment">// &#123;name: "An", des: "JS"&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="4">
<li><p>Object 转 Map</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">objToMap</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">of</span> <span class="built_in">Object</span>.keys(obj)) &#123;</span><br><span class="line">        map.set(key, obj[key])</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> map</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">objToMap(&#123;<span class="string">'name'</span>: <span class="string">'An'</span>, <span class="string">'des'</span>: <span class="string">'JS'</span>&#125;) <span class="comment">// Map &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="5">
<li><p>Map 转 JSON</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mapToJson</span>(<span class="params">map</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">JSON</span>.stringify([...map])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>().set(<span class="string">'name'</span>, <span class="string">'An'</span>).set(<span class="string">'des'</span>, <span class="string">'JS'</span>)</span><br><span class="line">mapToJson(map)	<span class="comment">// [["name","An"],["des","JS"]]</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="6">
<li><p>JSON 转 Map</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">jsonToStrMap</span>(<span class="params">jsonStr</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> objToMap(<span class="built_in">JSON</span>.parse(jsonStr));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">jsonToStrMap(<span class="string">'&#123;"name": "An", "des": "JS"&#125;'</span>) <span class="comment">// Map &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="4-WeakMap"><a href="#4-WeakMap" class="headerlink" title="4. WeakMap"></a>4. WeakMap</h3><p>WeakMap 对象是一组键值对的集合，其中的<strong>键是弱引用对象，而值可以是任意</strong>。</p>
<p><strong>注意，WeakMap 弱引用的只是键名，而不是键值。键值依然是正常引用。</strong></p>
<p>WeakMap 中，每个键对自己所引用对象的引用都是弱引用，在没有其他引用和该键引用同一对象，这个对象将会被垃圾回收（相应的key则变成无效的），所以，WeakMap 的 key 是不可枚举的。</p>
<p> 属性：</p>
<ul>
<li>constructor：构造函数</li>
</ul>
<p>方法：</p>
<ul>
<li>has(key)：判断是否有 key 关联对象</li>
<li>get(key)：返回key关联对象（没有则则返回 undefined）</li>
<li>set(key)：设置一组key关联对象</li>
<li>delete(key)：移除 key 的关联对象</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> myElement = <span class="built_in">document</span>.getElementById(<span class="string">'logo'</span>);</span><br><span class="line"><span class="keyword">let</span> myWeakmap = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"></span><br><span class="line">myWeakmap.set(myElement, &#123;<span class="attr">timesClicked</span>: <span class="number">0</span>&#125;);</span><br><span class="line"></span><br><span class="line">myElement.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> logoData = myWeakmap.get(myElement);</span><br><span class="line">  logoData.timesClicked++;</span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h3 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h3><ul>
<li>Set<ul>
<li>成员唯一、无序且不重复</li>
<li>[value,  value]，键值与键名是一致的（或者说只有键值，没有键名）</li>
<li>可以遍历，方法有：add、delete、has</li>
</ul>
</li>
<li>WeakSet<ul>
<li>成员都是对象</li>
<li>成员都是弱引用，可以被垃圾回收机制回收，可以用来保存DOM节点，不容易造成内存泄漏</li>
<li>不能遍历，方法有add、delete、has</li>
</ul>
</li>
<li>Map<ul>
<li>本质上是键值对的集合，类似集合</li>
<li>可以遍历，方法很多可以跟各种数据格式转换</li>
</ul>
</li>
<li>WeakMap<ul>
<li>只接受对象作为键名（null除外），不接受其他类型的值作为键名</li>
<li>键名是弱引用，键值可以是任意的，键名所指向的对象可以被垃圾回收，此时键名是无效的</li>
<li>不能遍历，方法有get、set、has、delete</li>
</ul>
</li>
</ul>
<h3 id="6-扩展：Object与Set、Map"><a href="#6-扩展：Object与Set、Map" class="headerlink" title="6. 扩展：Object与Set、Map"></a>6. 扩展：Object与Set、Map</h3><ol>
<li><p>Object 与 Set</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// Object</span></span><br><span class="line"><span class="keyword">const</span> properties1 = &#123;</span><br><span class="line">    <span class="string">'width'</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="string">'height'</span>: <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(properties1[<span class="string">'width'</span>]? <span class="literal">true</span>: <span class="literal">false</span>) <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Set</span></span><br><span class="line"><span class="keyword">const</span> properties2 = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">properties2.add(<span class="string">'width'</span>)</span><br><span class="line">properties2.add(<span class="string">'height'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(properties2.has(<span class="string">'width'</span>)) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Object 与 Map</p>
</li>
</ol>
<p>JS 中的对象（Object），本质上是键值对的集合（hash 结构）</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> data = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> element = <span class="built_in">document</span>.getElementsByClassName(<span class="string">'App'</span>);</span><br><span class="line"></span><br><span class="line">data[element] = <span class="string">'metadata'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(data[<span class="string">'[object HTMLCollection]'</span>]) <span class="comment">// "metadata"</span></span><br></pre></td></tr></table></figure>
<p>但当以一个DOM节点作为对象 data 的键，对象会被自动转化为字符串[Object HTMLCollection]，所以说，Object 结构提供了 <strong>字符串-值</strong> 对应，Map则提供了 <strong>值-值</strong> 的对应</p>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/09/22/JavaScript-event-loop/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/09/26/rn-device-debug/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
